package com.powernode.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powernode.constant.BusinessEnum;
import com.powernode.domain.Prod;
import com.powernode.domain.ProdTagReference;
import com.powernode.ex.handler.BusinessException;
import com.powernode.feign.SearchProdFeign;
import com.powernode.model.Result;
import com.powernode.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private SearchProdFeign searchProdFeign;

    /**
     * 根据分组标签分页查询商品
     *
     * @param current
     * @param size
     * @param tagId
     * @return
     */
    @Override
    public Page<Prod> loadWxProdPageByTagId(Long current, Long size, Long tagId) {
        //创建商品分页对象
        Page<Prod> prodPage = new Page<>(current, size);
        //远程调用: 根据分组标签分页查询商品与分组标签的关系
        Result<Page<ProdTagReference>> result = searchProdFeign.getProdTagReferencePageByTagId(current, size, tagId);
        //判断是否操作成功
        if (result.getCode().equals(BusinessEnum.OPERATION_FAIL.getCode())) {
            throw new BusinessException("远程调用: 根据分组标签分页查询商品与分组标签的关系失败");
        }
        //获取商品与分组标签的分页对象
        Page<ProdTagReference> prodTagReferencePage = result.getData();
        //从商品与分组标签分页对象中获取商品与分组标签关系记录
        List<ProdTagReference> prodTagReferenceList = prodTagReferencePage.getRecords();
        //判断商品与分组标签关系记录是否有值
        if (CollectionUtils.isEmpty(prodTagReferenceList) || prodTagReferenceList.size() == 0) {
            return prodPage;
        }
        //从商品与分组标签关系记录中获取商品id集合
        List<Long> prodIdList = prodTagReferenceList.stream().map(ProdTagReference::getProdId).collect(Collectors.toList());
        //远程调用: 根据商品id集合查询商品列表
        Result<List<Prod>> prodResult = searchProdFeign.getProdListByIds(prodIdList);
        //判断是否操作成功
        if (prodResult.getCode().equals(BusinessEnum.OPERATION_FAIL.getCode())) {
            throw new BusinessException("远程调用: 根据商品id集合查询商品列表失败");
        }
        //获取商品对象集合
        List<Prod> prods = prodResult.getData();
        //组装商品分页对象
        prodPage.setRecords(prods);
        prodPage.setTotal(prodTagReferencePage.getTotal());
        prodPage.setPages(prodTagReferencePage.getPages());
        return prodPage;
    }
}
